/*
 * @Author: hongbin
 * @Date: 2022-01-03 18:25:55
 * @LastEditors: hongbin
 * @LastEditTime: 2022-01-06 17:23:25
 * @Description: 城市 数据
 */
import { FC, ReactElement, useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import styled from "styled-components";
import ReactEcharts from "echarts-for-react";
import { registerMap } from "echarts";
import { getGeoJSON } from "../../utils";

interface IProps {}

const City: FC<IProps> = (): ReactElement => {
  const navigate = useNavigate();
  const { state } = useLocation();
  const [option, setOption] = useState<any>(null);

  useEffect(() => {
    // @ts-ignore
    if (!state || !state.name) {
      return navigate("/");
    }

    // @ts-ignore
    let name = state.name;
    let json = getGeoJSON(name);

    if (json) {
      const randomData = [];
      console.log(json);
      for (const {
        properties: { name },
      } of json.features) {
        // 生成随机数据
        if (name) {
          randomData.push({ name, value: Math.floor(Math.random() * 1000) });
        }
      }
      setOption(chartsOption(name, randomData));
      registerMap(name, json);
    }
  }, [navigate, state]);

  return (
    <Container>
      {option ? (
        <ReactEcharts
          option={option}
          style={{ width: "100%", height: "100%" }}
        />
      ) : null}
    </Container>
  );
};

export default City;

const Container = styled.div`
  width: 100%;
  height: calc(100vh - var(--header-height, 10vh));
  #cityCanvasArea {
    width: inherit;
    height: inherit;
  }
`;

const chartsOption = (
  name: string,
  data: Array<{ [key: string]: string | number }>
) => {
  // 计算data的max
  let max = data[0].value;
  for (let i = 1; i < data.length; i++) {
    if (max < data[i].value) {
      max = data[i].value;
    }
  }
  // 凑整
  max = Number("1".padEnd(max.toString().length + 1, "0"));

  return {
    title: {
      text: `${name}地图`,
    },
    tooltip: {
      trigger: "item",
      formatter: "{b}<br/>{c}",
    },

    visualMap: {
      min: 0,
      max,
      text: ["高", "低"],
      realtime: true,
      calculable: true,
      inRange: {
        color: ["lightskyblue", "orangered"],
      },
      type: "continuous",
    },
    series: [
      {
        name: `${name}数据`,
        type: "map",
        map: name,
        zoom: 0.8, //当前视角的缩放比例
        roam: true, //是否开启平游或缩放
        scaleLimit: {
          //滚轮缩放的极限控制
          min: 0.8,
          max: 2,
        },
        label: {
          show: false,
        },
        data,
        itemStyle: {
          shadowColor: "rgba(0, 0, 0, 0.3)",
          shadowBlur: 3,
          emphasis: {
            // borderWidth: 2,
            // borderColor: "rgba(0, 0, 0, 0.5)",
            areaColor: "orangered",
            shadowColor: "orangered",
            shadowBlur: 10,
          },
        },
      },
    ],
  };
};
